package cn.btks.resultintegration.achievements.service.impl;

import cn.btks.commonserver.pojo.PageList;
import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.FileUtil;
import cn.btks.commonserver.util.GeoUtils;
import cn.btks.commonserver.util.JwtUtil;
import cn.btks.resultintegration.achievements.pojo.*;
import cn.btks.resultintegration.achievements.repository.AchievementsFileTempRepository;
import cn.btks.resultintegration.achievements.repository.AchievementsTempRepository;
import cn.btks.resultintegration.achievements.repository.AchievementsTypeRepository;
import cn.btks.resultintegration.achievements.service.AchievementsTempService;
import cn.btks.resultintegration.achievements.service.TextAchievementsTempService;
import cn.btks.resultintegration.achievements.service.VectorFileCategoryService;
import cn.btks.resultintegration.catalog.pojo.Catalog;
import cn.btks.resultintegration.catalog.service.CatalogService;
import cn.btks.resultintegration.feign.FeignClient.BackManageClient;
import cn.btks.resultintegration.feign.FeignObject.City;
import cn.btks.resultintegration.feign.FeignObject.Unit;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @Author lijun
 * @Date 2021/2/20 9:11
 */
@Service
@Transactional
public class AchievementsTempServiceImpl implements AchievementsTempService {

    @Autowired
    AchievementsTempRepository achievementsTempRepository;

    @Autowired
    TextAchievementsTempService textAchievementsTempService;

    @Autowired
    CatalogService catalogService;

    @Autowired
    AchievementsTypeRepository achievementsTypeRepository;

    @Autowired
    AchievementsFileTempRepository achievementsFileTempRepository;

    @Autowired
    VectorFileCategoryService vectorFileCategoryService;

    @Autowired
    BackManageClient backManageClient;

    @Override
    public AchievementsTemp findById(Long id) {
        Optional<AchievementsTemp> optional = achievementsTempRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public ResultState findPage(Integer pageNumber, Integer pageSize, Integer isApproved) {
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Specification<AchievementsTemp> specification = new Specification<AchievementsTemp>() {
            @Override
            public Predicate toPredicate(Root<AchievementsTemp> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (isApproved != null) {
                    predicates.add(criteriaBuilder.equal(root.get("isApproved"), isApproved));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<AchievementsTemp> configPage = achievementsTempRepository.findAll(specification, pageRequest);
        if (configPage.getTotalElements() > 0) {
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState findPage1(Integer pageNumber, Integer pageSize, Integer isApproved, HttpServletRequest request) throws Exception {
        Long unitId = Long.valueOf(0);
        if(!Objects.isNull(request)){
            String token = request.getHeader("token");
            Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
            if (optional.isPresent()) {
                Claims claims = optional.get();
                Object obj = claims.get("unit");
                Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
                if (unit != null) {
                    unitId = unit.getCityId();
                }
            }
        }
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Long finalUnitId = unitId;
        Specification<AchievementsTemp> specification = new Specification<AchievementsTemp>() {
            @Override
            public Predicate toPredicate(Root<AchievementsTemp> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (isApproved != null) {
                    predicates.add(criteriaBuilder.equal(root.get("isApproved"), isApproved));
                }
                if (finalUnitId != 0) {
                    predicates.add(criteriaBuilder.equal(root.get("unitId"), finalUnitId));
                }
//                predicates.add(criteriaBuilder.equal(root.get("isHistory"), 0));
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<AchievementsTemp> configPage = achievementsTempRepository.findAll(specification, pageRequest);
        if (configPage.getTotalElements() > 0) {
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState findPage2(Integer pageNumber, Integer pageSize, Long cityId) {
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Specification<AchievementsTemp> specification = new Specification<AchievementsTemp>() {
            @Override
            public Predicate toPredicate(Root<AchievementsTemp> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (cityId != 0 && cityId != null) {
                    predicates.add(criteriaBuilder.equal(root.get("unitId"), cityId));
                }
                predicates.add(criteriaBuilder.equal(root.get("isApproved"), 1));
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<AchievementsTemp> configPage = achievementsTempRepository.findAll(specification, pageRequest);
        if (configPage.getTotalElements() > 0) {
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState save(AchievementsTemp achievementsTemp, MultipartFile multipartTextFile, List<MultipartFile> multipartVectorFiles, List<MultipartFile> multipartEvidenceFiles, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if (optionalClaims.isPresent()) {
            Claims claims = optionalClaims.get();
            String userName = claims.get("username").toString();
            String unitName = claims.get("unitName").toString();
            Object obj = claims.get("unit");
            Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if (unit != null) {
                achievementsTemp.setUnitId(unit.getCityId());
            }
            achievementsTemp.setReportUser(userName);
            achievementsTemp.setReportUnit(unitName);
        }
        Map<String, Object> objectMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> textResultMap = new HashMap<>();
        Map<String, Object> vectorResultMap = new HashMap<>();
        List<Map<String, Object>> vectorMapList = new ArrayList<>();
        List<Map<String, Object>> textMapList = new ArrayList<>();
        List<String> vectorResultList = new ArrayList<>();
        List<String> textResultList = new ArrayList<>();
        List<String> vectorSuccessResultList = new ArrayList<>();
        List<String> textSuccessResultList = new ArrayList<>();
        List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();
        List<AchievementsFileTemp> achievementsFileList = new ArrayList<>();
        List<TextAchievementsTemp> textAchievementsTempList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        AchievementsType achievementsVectorType = achievementsTypes.stream().filter(s -> s.getCode().equals("VECTOR")).findFirst().get();
        AchievementsType achievementsTextType = achievementsTypes.stream().filter(s -> s.getCode().equals("TEXT")).findFirst().get();
        AchievementsType achievementsEvidenceType = achievementsTypes.stream().filter(s -> s.getCode().equals("EVIDENCE")).findFirst().get();
        List<VectorFileCategory> vectorFileCategoryList = vectorFileCategoryService.findAll();
        String cityCodeText = "";
        String cityCodeVector = "";
        if (multipartVectorFiles != null && multipartEvidenceFiles != null) {
            vectorResultMap.put("false", vectorResultList);
            textResultMap.put("false", textResultList);
            vectorResultMap.put("true", vectorSuccessResultList);
            textResultMap.put("true", textSuccessResultList);
            vectorMapList.add(vectorResultMap);
            textMapList.add(textResultMap);
            String fileVectorPath = Constants.ACHIEVEMENTS_VECTOR_FILE;
            String fileTextPath = Constants.ACHIEVEMENTS_TEXT_FILE;
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;
            //解析数据，获取所属师ID
            Long cityId = Long.valueOf(0);
            //保存矢量文件
            Long fileCategory = Long.valueOf(0);
            if (multipartVectorFiles != null) {
                achievementsTemp.setTypeId(achievementsVectorType.getId());
                String fileServerPath = "";
                String uuid = UUID.randomUUID().toString();
                List<AchievementsFileTemp> achievementsFileTemps = new ArrayList<>();
                for (int i = 0; i < multipartVectorFiles.size(); i++) {
                    AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
                    String fjName = uuid + "_" + multipartVectorFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartVectorFiles.get(i).getOriginalFilename();
                    List<AchievementsFileTemp> fileTempList = achievementsFileTempRepository.findAllByFileName(fileOriginalFileName);
                    if (fileTempList != null && fileTempList.size() > 0) {
                        return new ResultState(StateInfo.FILE_EXIST_ERROR.getCode(), StateInfo.FILE_EXIST_ERROR.getMsg());
                    }
                    for (VectorFileCategory item : vectorFileCategoryList) {
                        boolean isContains = fileOriginalFileName.contains(item.getCode());
                        if (isContains) {
                            achievementsFile.setFileCategory(item.getId());
                            fileCategory = item.getId();
                            break;
                        }
                    }
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath + fjName;
                    String filePathFinal = fileVectorPath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartVectorFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        if (suffix.equals("shp")) {
                            //当为shp文件时，对其进行解析
                            fileServerPath = pathname;
                        }
                        if (suffix.equals("prj")) {
                            BufferedReader bufferedReader = new BufferedReader(new FileReader(pathname));
                            String line = null;
                            String fileContent = "";
                            while ((line = bufferedReader.readLine()) != null) {
                                fileContent = line;
                            }
                            if (fileContent.contains("Coordinate System 2000")) {
                                vectorSuccessResultList.add("坐标系无误。");
                            } else {
                                vectorResultList.add("坐标系错误。");
                            }
                        }
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsVectorType.getId());
                    achievementsFile.setIsHistory(0);
//                    achievementsFileList.add(achievementsFile);
                    achievementsFileTemps.add(achievementsFile);
                    achievementsFile.setContent(achievementsTemp.getContent());
                }
                if (achievementsFileTemps.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                objectMap = analysisVector1(fileServerPath, achievementsTemp);
                if (MapUtils.isNotEmpty(objectMap)) {
                    if (objectMap.containsKey("cityCode")) {
                        cityCodeVector = objectMap.get("cityCode").toString();
                        ResultState resultState = backManageClient.findAllCity();
                        if (resultState.getData() != null) {
                            List<City> cityList = new ArrayList<>();
                            Object data = resultState.getData();
                            cityList = com.alibaba.fastjson.JSONArray.parseArray(JSON.toJSONString(data), City.class);
                            if (cityList.size() > 0) {
                                String finalCityCodeText = cityCodeVector;
                                Optional<City> optional = cityList.stream().filter(s -> s.getCode().equals(finalCityCodeText)).findFirst();
                                if (optional.isPresent()) {
                                    cityId = optional.get().getId();
                                }
                            }
                        }
                        for (AchievementsFileTemp item : achievementsFileTemps) {
                            item.setCityId(cityId);
                        }
                    }
                }
                achievementsFileList.addAll(achievementsFileTemps);
                achievementsTemp.setFiles(achievementsFileList);
                for (AchievementsFileTemp file : achievementsFileList) {
                    file.setAchievements(achievementsTemp);
                }
            } else {
                vectorResultList.add("审核不通过，缺少矢量文件");
                resultMap.put("VECTOR", vectorResultList);
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            //保存管控单元清单文本文件
            if (multipartTextFile != null) {
                textAchievementsTempList = analysisTextFile(fileTextPath, achievementsFileList, multipartTextFile, achievementsTemp, achievementsTextType, cityId, fileCategory, request);
            }
            //佐证材料
            if (multipartEvidenceFiles != null) {
                String fileServerPath = "";
                List<AchievementsFileTemp> achievementsFileTemps = new ArrayList<>();
                for (int i = 0; i < multipartEvidenceFiles.size(); i++) {
                    String uuid = UUID.randomUUID().toString();
                    AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
                    String fjName = uuid + "_" + multipartEvidenceFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartEvidenceFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileEvidencePath + fjName;
                    String filePathFinal = fileEvidencePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartEvidenceFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFileCategory(fileCategory);
                    achievementsFile.setCityId(cityId);
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsEvidenceType.getId());
                    achievementsFile.setIsHistory(0);
                    achievementsFileList.add(achievementsFile);
                    achievementsFileTemps.add(achievementsFile);
                    achievementsFile.setContent(achievementsTemp.getContent());
                }
                if (achievementsFileTemps.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                for (AchievementsFileTemp file : achievementsFileTemps) {
                    file.setAchievements(achievementsTemp);
                }

//                boolean result = generateFile(fileEvidencePath, achievementsFileList, multipartEvidenceFile, achievementsTemp, achievementsEvidenceType, cityId, request);
//                if (!result) {
//                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
//                }
                textSuccessResultList.add("具备佐证材料。");
            } else {
                textResultList.add("审核不通过，缺少佐证材料文件");
                resultMap.put("TEXT", textResultList);
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            if (objectMap.containsKey("error")) {
                //审核不通过
                achievementsTemp.setIsApproved(0);
                List<String> errors = (List<String>) objectMap.get("error");
                String errorStr = "矢量文件解析出错：";
                for (String item : errors) {
                    errorStr += item + " ";
                }
                achievementsTemp.setVerifyContent(errorStr);
                vectorResultList.add("矢量文件解析错误：" + errorStr);
//                resultMap.put("VECTOR",vectorResultList);
//                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), errorStr);
            } else {
                vectorSuccessResultList.add("矢量文件解析成功。");
            }
            if (objectMap.containsKey("attribute")) {
                //校验管控清单和矢量文件属性是否一一对应
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
                if (textAchievementsTempList.size() > 0) {
                    String hjgkdybm = "";
                    boolean isExist = false;
                    for (EnvironmentAttribute item : environmentAttributes) {
                        boolean result = textAchievementsTempList.stream().anyMatch(s -> s.getUnitCode().trim().equals(item.getHJDYBM()));
                        if (!result) {
                            isExist = true;
                            hjgkdybm += item.getHJDYBM() + "/";
                        }
                    }
                    if (isExist) {
                        textResultList.add("环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybm);
//                        resultMap.put("TEXT", textMapList);
//                            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "审核不通过，环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybm);
                    } else {
                        textSuccessResultList.add("具备管控清单文件。");
                        textSuccessResultList.add("环境管控清单和矢量数据相匹配。");
                    }
                }
            }
            resultMap.put("TEXT", textMapList);
            resultMap.put("VECTOR", vectorMapList);
            if (textResultList.size() > 0 || vectorResultList.size() > 0) {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
//            if(MapUtils.isNotEmpty(resultMap)){
//                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
//            }
            //审核中
            achievementsTemp.setIsApproved(2);
            achievementsTemp.setVerifyContent("系统审核通过");
            //矢量属性解析后数据
            if (objectMap.containsKey("attribute")) {
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
            }
            //保存文本清单数据
            if (textAchievementsTempList != null) {
                textAchievementsTempService.saveAll(textAchievementsTempList);
            }
            achievementsTemp.setUploadDate(new Date());
            achievementsTemp.setVerifyType(0);
            AchievementsTemp achievementsTemp1 = achievementsTempRepository.save(achievementsTemp);
            return achievementsTemp1 != null ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), resultMap) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "保存成果失败");
        } else {
            textResultList.add("文件材料不完整");
            resultMap.put("TEXT", textResultList);
            //审核不通过
            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState save1(AchievementsTemp achievementsTemp, List<MultipartFile> multipartEvidenceFile, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if (optionalClaims.isPresent()) {
            Claims claims = optionalClaims.get();
            String userName = claims.get("username").toString();
            String unitName = claims.get("unitName").toString();
            Object obj = claims.get("unit");
            Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if (unit != null) {
                achievementsTemp.setUnitId(unit.getCityId());
            }
            achievementsTemp.setReportUser(userName);
            achievementsTemp.setReportUnit(unitName);
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<String> textResultList = new ArrayList<>();
        List<String> textSuccessResultList = new ArrayList<>();
        List<AchievementsFileTemp> achievementsFileList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        AchievementsType achievementsEvidenceType = achievementsTypes.stream().filter(s -> s.getCode().equals("EVIDENCE")).findFirst().get();
        if (multipartEvidenceFile != null) {
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;
            //解析数据，获取所属师ID
            Long cityId = Long.valueOf(0);
            //保存矢量文件
            Long fileCategory = Long.valueOf(0);
            //佐证材料
            if (multipartEvidenceFile != null) {
                String fileServerPath = "";
                List<AchievementsFileTemp> achievementsFileTemps = new ArrayList<>();
                for (int i = 0; i < multipartEvidenceFile.size(); i++) {
                    String uuid = UUID.randomUUID().toString();
                    AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
                    String fjName = uuid + "_" + multipartEvidenceFile.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartEvidenceFile.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileEvidencePath + fjName;
                    String filePathFinal = fileEvidencePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartEvidenceFile.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFileCategory(fileCategory);
                    achievementsFile.setCityId(cityId);
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsEvidenceType.getId());
                    achievementsFile.setIsHistory(0);
                    achievementsFileList.add(achievementsFile);
                    achievementsFileTemps.add(achievementsFile);
                    achievementsFile.setContent(achievementsTemp.getContent());
                }
                if (achievementsFileTemps.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                for (AchievementsFileTemp file : achievementsFileTemps) {
                    file.setAchievements(achievementsTemp);
                }
                textSuccessResultList.add("具备佐证材料。");
            } else {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            achievementsTemp.setFiles(achievementsFileList);
            //审核中
            achievementsTemp.setIsApproved(2);
            achievementsTemp.setVerifyContent("系统审核通过");

            achievementsTemp.setUploadDate(new Date());
            achievementsTemp.setVerifyType(0);
            AchievementsTemp achievementsTemp1 = achievementsTempRepository.save(achievementsTemp);
            return achievementsTemp1 != null ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), resultMap) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "保存成果失败");
        } else {
            textResultList.add("文件材料不完整");
            resultMap.put("TEXT", textResultList);
            //审核不通过
            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState update(AchievementsTemp achievementsTemp, MultipartFile multipartTextFile, List<MultipartFile> multipartVectorFiles, List<MultipartFile> multipartEvidenceFiles, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optionalClaims = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if (optionalClaims.isPresent()) {
            Claims claims = optionalClaims.get();
            String userName = claims.get("username").toString();
            String unitName = claims.get("unitName").toString();
            Object obj = claims.get("unit");
            Unit unit = com.alibaba.fastjson.JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if (unit != null) {
                achievementsTemp.setUnitId(unit.getCityId());
            }
            achievementsTemp.setReportUser(userName);
            achievementsTemp.setReportUnit(unitName);
        }
        Map<String, Object> objectMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> textResultMap = new HashMap<>();
        Map<String, Object> vectorResultMap = new HashMap<>();
        List<Map<String, Object>> vectorMapList = new ArrayList<>();
        List<Map<String, Object>> textMapList = new ArrayList<>();
        List<String> vectorResultList = new ArrayList<>();
        List<String> textResultList = new ArrayList<>();
        List<String> vectorSuccessResultList = new ArrayList<>();
        List<String> textSuccessResultList = new ArrayList<>();
        List<EnvironmentAttribute> environmentAttributes = new ArrayList<>();
        List<AchievementsFileTemp> achievementsFileList = new ArrayList<>();
        List<TextAchievementsTemp> textAchievementsTempList = new ArrayList<>();
        List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
        AchievementsType achievementsVectorType = achievementsTypes.stream().filter(s -> s.getCode().equals("VECTOR")).findFirst().get();
        AchievementsType achievementsTextType = achievementsTypes.stream().filter(s -> s.getCode().equals("TEXT")).findFirst().get();
        AchievementsType achievementsEvidenceType = achievementsTypes.stream().filter(s -> s.getCode().equals("EVIDENCE")).findFirst().get();
        List<VectorFileCategory> vectorFileCategoryList = vectorFileCategoryService.findAll();
        String cityCodeText = "";
        String cityCodeVector = "";
        if (multipartVectorFiles != null && multipartEvidenceFiles != null) {
            vectorResultMap.put("false", vectorResultList);
            textResultMap.put("false", textResultList);
            vectorResultMap.put("true", vectorSuccessResultList);
            textResultMap.put("true", textSuccessResultList);
            vectorMapList.add(vectorResultMap);
            textMapList.add(textResultMap);
            String fileVectorPath = Constants.ACHIEVEMENTS_VECTOR_FILE;
            String fileTextPath = Constants.ACHIEVEMENTS_TEXT_FILE;
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;
            //解析数据，获取所属师ID
            Long cityId = Long.valueOf(0);
            //保存矢量文件
            Long fileCategory = Long.valueOf(0);
            if (multipartVectorFiles != null) {
                achievementsTemp.setTypeId(achievementsVectorType.getId());
                String fileServerPath = "";
                String uuid = UUID.randomUUID().toString();
                List<AchievementsFileTemp> achievementsFileTemps = new ArrayList<>();
                for (int i = 0; i < multipartVectorFiles.size(); i++) {
                    AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
                    String fjName = uuid + "_" + multipartVectorFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartVectorFiles.get(i).getOriginalFilename();
                    for (VectorFileCategory item : vectorFileCategoryList) {
                        boolean isContains = fileOriginalFileName.contains(item.getCode());
                        if (isContains) {
                            achievementsFile.setFileCategory(item.getId());
                            fileCategory = item.getId();
                            break;
                        }
                    }
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileVectorPath + fjName;
                    String filePathFinal = fileVectorPath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartVectorFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        if (suffix.equals("shp")) {
                            //当为shp文件时，对其进行解析
                            fileServerPath = pathname;
                        }
                        if (suffix.equals("prj")) {
                            BufferedReader bufferedReader = new BufferedReader(new FileReader(pathname));
                            String line = null;
                            String fileContent = "";
                            while ((line = bufferedReader.readLine()) != null) {
                                fileContent = line;
                            }
                            if (fileContent.contains("Coordinate System 2000")) {
                                vectorSuccessResultList.add("坐标系无误。");
                            } else {
                                vectorResultList.add("坐标系错误。");
                            }
                        }
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsVectorType.getId());
                    achievementsFile.setIsHistory(0);
//                    achievementsFileList.add(achievementsFile);
                    achievementsFileTemps.add(achievementsFile);
                    achievementsFile.setContent(achievementsTemp.getContent());
                }
                if (achievementsFileTemps.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                objectMap = analysisVector1(fileServerPath, achievementsTemp);
                if (MapUtils.isNotEmpty(objectMap)) {
                    if (objectMap.containsKey("cityCode")) {
                        cityCodeVector = objectMap.get("cityCode").toString();
                        ResultState resultState = backManageClient.findAllCity();
                        if (resultState.getData() != null) {
                            List<City> cityList = new ArrayList<>();
                            Object data = resultState.getData();
                            cityList = com.alibaba.fastjson.JSONArray.parseArray(JSON.toJSONString(data), City.class);
                            if (cityList.size() > 0) {
                                String finalCityCodeText = cityCodeVector;
                                Optional<City> optional = cityList.stream().filter(s -> s.getCode().equals(finalCityCodeText)).findFirst();
                                if (optional.isPresent()) {
                                    cityId = optional.get().getId();
                                }
                            }
                        }
                        for (AchievementsFileTemp item : achievementsFileTemps) {
                            item.setCityId(cityId);
                        }
                    }
                }
                achievementsFileList.addAll(achievementsFileTemps);
                achievementsTemp.setFiles(achievementsFileList);
                for (AchievementsFileTemp file : achievementsFileList) {
                    file.setAchievements(achievementsTemp);
                }
            } else {
                vectorResultList.add("审核不通过，缺少矢量文件");
                resultMap.put("VECTOR", vectorResultList);
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            //保存管控单元清单文本文件
            if (multipartTextFile != null) {
                textAchievementsTempList = analysisTextFile(fileTextPath, achievementsFileList, multipartTextFile, achievementsTemp, achievementsTextType, cityId, fileCategory, request);
            }
            //佐证材料
            if (multipartEvidenceFiles != null) {
                String fileServerPath = "";
                List<AchievementsFileTemp> achievementsFileTemps = new ArrayList<>();
                for (int i = 0; i < multipartEvidenceFiles.size(); i++) {
                    String uuid = UUID.randomUUID().toString();
                    AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
                    String fjName = uuid + "_" + multipartEvidenceFiles.get(i).getOriginalFilename();
                    String fileOriginalFileName = multipartEvidenceFiles.get(i).getOriginalFilename();
                    String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileEvidencePath + fjName;
                    String filePathFinal = fileEvidencePath + fjName;
                    System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                    if (FileUtil.fileUpload(multipartEvidenceFiles.get(i), pathname)) {
                        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                    }
                    String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                    if (!StringUtils.isEmpty(suffix)) {
                        achievementsFile.setFileType(suffix);
                    }
                    achievementsFile.setFileCategory(fileCategory);
                    achievementsFile.setCityId(cityId);
                    achievementsFile.setFilePath(filePathFinal);
                    achievementsFile.setFileName(fileOriginalFileName);
                    achievementsFile.setAchievementsTypeId(achievementsEvidenceType.getId());
                    achievementsFile.setIsHistory(0);
                    achievementsFileList.add(achievementsFile);
                    achievementsFileTemps.add(achievementsFile);
                    achievementsFile.setContent(achievementsTemp.getContent());
                }
                if (achievementsFileTemps.size() <= 0) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                for (AchievementsFileTemp file : achievementsFileTemps) {
                    file.setAchievements(achievementsTemp);
                }

//                boolean result = generateFile(fileEvidencePath, achievementsFileList, multipartEvidenceFile, achievementsTemp, achievementsEvidenceType, cityId, request);
//                if (!result) {
//                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
//                }
                textSuccessResultList.add("具备佐证材料。");
            } else {
                textResultList.add("审核不通过，缺少佐证材料文件");
                resultMap.put("TEXT", textResultList);
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
            if (objectMap.containsKey("error")) {
                //审核不通过
                achievementsTemp.setIsApproved(0);
                List<String> errors = (List<String>) objectMap.get("error");
                String errorStr = "矢量文件解析出错：";
                for (String item : errors) {
                    errorStr += item + " ";
                }
                achievementsTemp.setVerifyContent(errorStr);
                vectorResultList.add("矢量文件解析错误：" + errorStr);
//                resultMap.put("VECTOR",vectorResultList);
//                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), errorStr);
            } else {
                vectorSuccessResultList.add("矢量文件解析成功。");
            }
            if (objectMap.containsKey("attribute")) {
                //校验管控清单和矢量文件属性是否一一对应
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
                if (textAchievementsTempList.size() > 0) {
                    String hjgkdybm = "";
                    boolean isExist = false;
                    for (EnvironmentAttribute item : environmentAttributes) {
                        boolean result = textAchievementsTempList.stream().anyMatch(s -> s.getUnitCode().trim().equals(item.getHJDYBM()));
                        if (!result) {
                            isExist = true;
                            hjgkdybm += item.getHJDYBM() + "/";
                        }
                    }
                    if (isExist) {
                        textResultList.add("环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybm);
//                        resultMap.put("TEXT", textMapList);
//                            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "审核不通过，环境管控清单中的数据和矢量数据中的属性不是一一对应。编码：" + hjgkdybm);
                    } else {
                        textSuccessResultList.add("具备管控清单文件。");
                        textSuccessResultList.add("环境管控清单和矢量数据相匹配。");
                        ;
                    }
                }
            }
            resultMap.put("TEXT", textMapList);
            resultMap.put("VECTOR", vectorMapList);
            if (textResultList.size() > 0 || vectorResultList.size() > 0) {
                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
            }
//            if(MapUtils.isNotEmpty(resultMap)){
//                return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
//            }
            //审核中
            achievementsTemp.setIsApproved(2);
            achievementsTemp.setVerifyContent("系统审核通过");
            //矢量属性解析后数据
            if (objectMap.containsKey("attribute")) {
                environmentAttributes = (List<EnvironmentAttribute>) objectMap.get("attribute");
            }
            //保存文本清单数据
            if (textAchievementsTempList != null) {
                textAchievementsTempService.saveAll(textAchievementsTempList);
            }
            achievementsTemp.setUploadDate(new Date());
            achievementsTemp.setVerifyType(0);
            achievementsFileTempRepository.updateFileIsHistory(achievementsTemp.getId(), 1);
            AchievementsTemp achievementsTemp1 = achievementsTempRepository.save(achievementsTemp);
            return achievementsTemp1 != null ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), resultMap) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), "保存成果失败");
        } else {
            textResultList.add("文件材料不完整");
            resultMap.put("TEXT", textResultList);
            //审核不通过
            return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState manualVerify(Integer isApproved, String verifyContent, Long achievementTempId, HttpServletRequest request) throws Exception {
        Optional<AchievementsTemp> optional1 = achievementsTempRepository.findById(achievementTempId);
        if (optional1.isPresent()) {
            String token = request.getHeader("token");
            Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
            if (optional.isPresent()) {
                Claims claims = optional.get();
                String userName = claims.get("username").toString();
                String unitName = claims.get("unitName").toString();
                achievementsTempRepository.updateVerifyUser(userName, unitName, achievementTempId);
            }
            if (isApproved.equals(1)) {
                verifyContent = "人工审核通过：" + verifyContent;
            } else {
                verifyContent = "人工审核不通过：" + verifyContent;
            }
            int result = achievementsTempRepository.manualVerify(isApproved, verifyContent, achievementTempId, new Date());
            return result > 0 ? new ResultState(StateInfo.SAVE_VERIFY_OK.getCode(), StateInfo.SAVE_VERIFY_OK.getMsg(), result) :
                    new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_VERIFY_ERROR.getCode(), StateInfo.SAVE_VERIFY_ERROR.getMsg());
    }

    /**
     * 生成文件
     *
     * @param filePath
     * @param achievementsFileTemps
     * @param multipartFile
     */
    private boolean generateFile(String filePath, List<AchievementsFileTemp> achievementsFileTemps, MultipartFile multipartFile, AchievementsTemp achievementsTemp, AchievementsType achievementsType, Long cityId, HttpServletRequest request) {
        String fileServerPath = "";
        String uuid = UUID.randomUUID().toString();
        AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
        String fjName = uuid + "_" + multipartFile.getOriginalFilename();
        String fileOriginalFileName = multipartFile.getOriginalFilename();
        String pathname = request.getSession(true).getServletContext().getRealPath("//") + filePath + fjName;
        String filePathFinal = filePath + fjName;
        System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
        if (FileUtil.fileUpload(multipartFile, pathname)) {
            return false;
        }
        String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
        if (!StringUtils.isEmpty(suffix)) {
            if (suffix.equals("shp")) {
                //当为shp文件时，对其进行解析
                fileServerPath = pathname;
            }
            achievementsFile.setFileType(suffix);
        }
        achievementsFile.setFilePath(filePathFinal);
        achievementsFile.setFileName(fileOriginalFileName);
        achievementsFile.setAchievementsTypeId(achievementsType.getId());
        achievementsFile.setIsHistory(0);
        achievementsFileTemps.add(achievementsFile);
        achievementsFile.setContent(achievementsTemp.getContent());
        achievementsTemp.setFiles(achievementsFileTemps);
        for (AchievementsFileTemp file : achievementsFileTemps) {
            file.setAchievements(achievementsTemp);
        }
        return true;
    }

    /**
     * 解析文本文件
     *
     * @param filePath
     * @param achievementsFileTemps
     * @param multipartFile
     */
    private List<TextAchievementsTemp> analysisTextFile(String filePath, List<AchievementsFileTemp> achievementsFileTemps, MultipartFile multipartFile, AchievementsTemp achievementsTemp, AchievementsType achievementsType, Long cityId, Long fileCategory, HttpServletRequest request) throws IOException {
        List<TextAchievementsTemp> textAchievementsList = new ArrayList<>();
        String fileServerPath = "";
        String uuid = UUID.randomUUID().toString();
        AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
        String fjName = uuid + "_" + multipartFile.getOriginalFilename();
        String fileOriginalFileName = multipartFile.getOriginalFilename();
        String pathname = request.getSession(true).getServletContext().getRealPath("//") + filePath + fjName;
        String filePathFinal = filePath + fjName;
        System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
        if (!FileUtil.fileUpload(multipartFile, pathname)) {
            File file = new File(pathname);
            if (file.exists()) {
                pathname = file.getAbsolutePath();
            }
            //Excel工具项
            InputStream inputStream = new FileInputStream(pathname);
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    continue;
                }
                TextAchievementsTemp textAchievements = new TextAchievementsTemp();
                //设置单元格类型
                row.getCell(0).setCellType(CellType.STRING);
                //序号
                String serialNum = row.getCell(0).getStringCellValue();
                //环境管控单元编码
                String unitCode = row.getCell(1).getStringCellValue();
                //单元名称
                String unitName = row.getCell(2).getStringCellValue();
                //省
                String province = row.getCell(3).getStringCellValue();
                //师
                String division = row.getCell(4).getStringCellValue();
                //团
                String regiment = row.getCell(5).getStringCellValue();
                //管控单元分类
                String unitClassify = row.getCell(6).getStringCellValue();
                //空间布局约束
                String spaceRestrain = row.getCell(7).getStringCellValue();
                //污染物排放管控
                String pollutantRestrain = row.getCell(8).getStringCellValue();
                //环境风险防控
                String environmentRestrain = row.getCell(9).getStringCellValue();
                //资源利用效率
                String resourceUtilization = row.getCell(10).getStringCellValue();

                textAchievements.setUnitCode(unitCode);
                textAchievements.setUnitName(unitName);
                textAchievements.setProvince(province);
                textAchievements.setDivision(division);
                textAchievements.setRegiment(regiment);
                textAchievements.setUnitClassify(unitClassify);
                textAchievements.setSpaceRestrain(spaceRestrain);
                textAchievements.setPollutantRestrain(pollutantRestrain);
                textAchievements.setEnvironmentRestrain(environmentRestrain);
                textAchievements.setResourceUtilization(resourceUtilization);
                textAchievementsList.add(textAchievements);
            }
        } else {
            return null;
        }
        String cityCodeText = "";
        if (textAchievementsList != null && textAchievementsList.size() > 0) {
            boolean isExist = false;
            for (int i = 0; i < textAchievementsList.size(); i++) {
                String unitCode = textAchievementsList.get(i).getUnitCode();
                if (!StringUtils.isEmpty(unitCode)) {
                    cityCodeText = unitCode.substring(2, 6);
                    if (cityCodeText.equals("6590")) {
                        continue;
                    } else {
                        isExist = true;
                    }
                    if (isExist) {
                        cityCodeText = unitCode.substring(2, 6);
                    } else {
                        cityCodeText = unitCode.substring(2, 8);
                    }
                    ResultState resultState = backManageClient.findAllCity();
                    if (resultState.getData() != null) {
                        List<City> cityList = new ArrayList<>();
                        Object data = resultState.getData();
                        cityList = com.alibaba.fastjson.JSONArray.parseArray(JSON.toJSONString(data), City.class);
                        if (cityList.size() > 0) {
                            String finalCityCodeText = cityCodeText;
                            Optional<City> optional = cityList.stream().filter(s -> s.getCode().equals(finalCityCodeText)).findFirst();
                            if (optional.isPresent()) {
                                cityId = optional.get().getId();
                                break;
                            }
                        }
                    }
                }
            }
        }
        String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
        if (!StringUtils.isEmpty(suffix)) {
            if (suffix.equals("shp")) {
                //当为shp文件时，对其进行解析
                fileServerPath = pathname;
            }
            achievementsFile.setFileType(suffix);
        }
        achievementsFile.setFileCategory(fileCategory);
        achievementsFile.setCityId(cityId);
        achievementsFile.setFilePath(filePathFinal);
        achievementsFile.setFileName(fileOriginalFileName);
        achievementsFile.setAchievementsTypeId(achievementsType.getId());
        achievementsFile.setIsHistory(0);
        achievementsFileTemps.add(achievementsFile);
        achievementsFile.setContent(achievementsTemp.getContent());
        achievementsTemp.setFiles(achievementsFileTemps);
        for (AchievementsFileTemp file : achievementsFileTemps) {
            file.setAchievements(achievementsTemp);
        }
        return textAchievementsList;
    }

    /**
     * 解析矢量文件数据
     *
     * @param filePath
     * @param achievements
     * @return
     */
    private Map<String, Object> analysisVector1(String filePath, AchievementsTemp achievements) {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> errors = new ArrayList<>();
        List<EnvironmentAttribute> environmentAttributeList = new ArrayList<>();
        //矢量数据时，解析矢量文件
        String jsonString = "";
        String HJDYBM = "";
        String cityCode = "";
        String HJDYBMTemp = "";
        String HJDYBMTemp1 = "";
        if (!StringUtils.isEmpty(filePath)) {
            JSONArray shpFileAttributes = GeoUtils.getShpFileAttributes(filePath);
            if (shpFileAttributes.size() > 0) {
                boolean isExist = false;
                int flagInt = 0;
                int flagInt1 = 0;
                for (int i = 0; i < shpFileAttributes.size(); i++) {
                    JSONObject object = (JSONObject) shpFileAttributes.get(i);
                    if (object.containsKey(Constants.HJYSGKFQBM) || object.containsKey(Constants.HJGKDYBM)) {
                        EnvironmentAttribute environmentAttribute = new EnvironmentAttribute();
                        if (object.containsKey(Constants.HJYSGKFQBM)) {
                            HJDYBM = object.get(Constants.HJYSGKFQBM).toString();
                            if (StringUtils.isEmpty(HJDYBM)) {
                                flagInt++;
                                if (flagInt <= 1) {
                                    errors.add("存在环境要素管控分区编码为空。");
                                }
                                continue;
                            }
                            cityCode = HJDYBM.substring(2, 6);
                            if (cityCode.equals("6590")) {
                                HJDYBMTemp = HJDYBM;
                            } else {
                                isExist = true;
                                HJDYBMTemp1 = HJDYBM;
                            }
                            if (HJDYBM.length() != 15) {
                                errors.add(HJDYBM + ":" + "环境要素管控分区编码长度不正确。");
                            }
                            if (!StringUtils.isEmpty(HJDYBM)) {
                                environmentAttribute.setHJDYBM(HJDYBM);
                                String HJYSGKFQMC = object.get(Constants.HJYSGKFQMC).toString();
                                String catalogCode = HJDYBM.substring(8, 11);//截取对应目录代码
                                if (StringUtils.isEmpty(HJYSGKFQMC) || StringUtils.isEmpty(catalogCode)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区名称或编码中对应目录编码不正确。");
                                }
                                environmentAttribute.setHJDYMC(HJYSGKFQMC);
                                if (!StringUtils.isEmpty(catalogCode)) {
                                    Catalog catalog = null;
                                    if (catalogCode.equals("1") || catalogCode.equals("2") || catalogCode.equals("3")) {
                                        catalog = catalogService.findByCode("4");
                                    } else {
                                        catalog = catalogService.findLikeKeyCode(catalogCode);
                                    }
                                    if (catalog != null) {
                                        achievements.setCatalogId(catalog.getId());
                                        environmentAttribute.setCatalogId(catalog.getId());
                                    } else {
                                        errors.add(HJDYBM + ":" + "环境要素管控分区编码中对应目录编码不正确。");
                                    }
                                }
                                String hjysdm = HJDYBM.substring(9, 10);//截取环境要素代码
                                switch (hjysdm) {
                                    case "1"://生态
                                    case "3"://大气
                                    case "4"://土壤
                                    case "5"://自然资源
                                        String GKQFL = object.get("GKQFL").toString();
                                        String HJYS = object.get("HJYS").toString();
                                        if (StringUtils.isEmpty(GKQFL) || StringUtils.isEmpty(HJYS)) {
                                            errors.add(HJDYBM + ":" + "环境要素管控分区编码中管控区分类或环境要素编码不正确。");
                                        }
                                        environmentAttribute.setGKQFL(GKQFL);
                                        environmentAttribute.setHJYS(HJYS);
                                        environmentAttribute.setTypeId(Long.valueOf(2));
                                        break;
                                    case "2"://水
                                        String LYMC = object.get("LYMC").toString();
                                        String HDMC = object.get("HDMC").toString();
                                        String KZDMQDJD = object.get("KZDMQDJD").toString();
                                        String KZDMQDWD = object.get("KZDMQDWD").toString();
                                        String KZDMZDJD = object.get("KZDMZDJD").toString();
                                        String KZDMZDWD = object.get("KZDMZDWD").toString();
                                        if (StringUtils.isEmpty(LYMC) || StringUtils.isEmpty(HDMC) || StringUtils.isEmpty(KZDMQDJD) || StringUtils.isEmpty(KZDMQDWD) || StringUtils.isEmpty(KZDMZDJD) || StringUtils.isEmpty(KZDMZDWD)) {
                                            errors.add(HJDYBM + ":" + "环境要素管控分区编码中流域名称或河段名称或控制断面起点经度或控制断面起点维度或控制断面终点经度或控制断面终点维度编码不正确。");
                                        }
                                        environmentAttribute.setLYMC(LYMC);
                                        environmentAttribute.setHDMC(HDMC);
                                        environmentAttribute.setKZDMQDJD(KZDMQDJD);
                                        environmentAttribute.setKZDMQDWD(KZDMQDWD);
                                        environmentAttribute.setKZDMZDJD(KZDMZDJD);
                                        environmentAttribute.setKZDMZDWD(KZDMZDWD);
                                        environmentAttribute.setTypeId(Long.valueOf(3));
                                        break;
                                    default:
                                        errors.add(HJDYBM + ":" + "环境要素管控分区要素编码不正确。");
                                        break;
                                }
                                String PROV = object.get("PROV").toString();
                                String CITY = object.get("CITY").toString();
                                String COUNTY = object.get("COUNTY").toString();
                                String YSXL = object.get("YSXL").toString();
                                if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY) || StringUtils.isEmpty(YSXL)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区行政区划或要素细类编码不正确。");
                                }
                                environmentAttribute.setPROV(PROV);
                                environmentAttribute.setCITY(CITY);
                                environmentAttribute.setCOUNTY(COUNTY);
                                environmentAttribute.setYSXL(YSXL);
                                environmentAttribute.setShapeArea(object.get("SHAPE_Area").toString());
                                environmentAttribute.setShapeLeng(object.get("SHAPE_Leng").toString());
                            } else {
                                errors.add("环境管控编码为空。");
                            }
                        }
                        if (object.containsKey(Constants.HJGKDYBM)) {
                            HJDYBM = object.get(Constants.HJGKDYBM).toString();
                            if (StringUtils.isEmpty(HJDYBM)) {
                                flagInt1++;
                                if (flagInt1 <= 1) {
                                    errors.add("环境管控单元编码编码为空。");
                                }
                                continue;
                            }
                            cityCode = HJDYBM.substring(2, 6);
                            if (cityCode.equals("6590")) {
                                HJDYBMTemp = HJDYBM;
                            } else {
                                isExist = true;
                                HJDYBMTemp1 = HJDYBM;
                            }
                            if (HJDYBM.length() != 13) {
                                errors.add(HJDYBM + ":" + "环境管控单元编码编码长度不正确。");
                            }
                            if (!StringUtils.isEmpty(HJDYBM)) {
                                environmentAttribute.setHJDYBM(HJDYBM);
                                String HJGKDYMC = object.get(Constants.HJGKDYMC).toString();
                                String catalogCode = HJDYBM.substring(8, 9);//截取对应目录代码
                                if (StringUtils.isEmpty(HJGKDYMC) || StringUtils.isEmpty(catalogCode)) {
                                    errors.add(HJDYBM + ":" + "环境管控单元名称或编码中对应目录编码不正确。");
                                }
                                environmentAttribute.setHJDYMC(HJGKDYMC);
                                if (!StringUtils.isEmpty(catalogCode)) {
                                    Catalog catalog = null;
                                    Catalog catalog1 = catalogService.findByKeyCode(catalogCode);
                                    if(catalogCode.equals("1") || catalogCode.equals("2") || catalogCode.equals("3")){
                                        catalog = catalogService.findByCode("4");
                                    }else {
                                        catalog = catalogService.findByKeyCode(catalogCode);
                                    }
                                    if(catalog1 != null){
                                        environmentAttribute.setCatalogId(catalog1.getId());
                                    }else {
                                        errors.add(HJDYBM + ":" + "环境管控单元编码中对应目录编码不正确。");
                                    }
                                    if (catalog != null) {
                                        achievements.setCatalogId(catalog.getId());
                                    }
                                }
                                String REMARKS = object.get("REMARKS").toString();
                                String PROV = object.get("PROV").toString();
                                String CITY = object.get("CITY").toString();
                                String COUNTY = object.get("COUNTY").toString();
                                String GKDYFL = object.get("GKDYFL").toString();
                                if (StringUtils.isEmpty(PROV) || StringUtils.isEmpty(CITY) || StringUtils.isEmpty(COUNTY) || StringUtils.isEmpty(GKDYFL)) {
                                    errors.add(HJDYBM + ":" + "环境要素管控分区行政区划或管控单元分类编码不正确。");
                                }
                                environmentAttribute.setTypeId(Long.valueOf(1));
                                environmentAttribute.setRemarks(REMARKS);
                                environmentAttribute.setPROV(PROV);
                                environmentAttribute.setCITY(CITY);
                                environmentAttribute.setCOUNTY(COUNTY);
                                environmentAttribute.setGKDYFL(GKDYFL);
                                environmentAttribute.setShapeArea(object.get("Shape_Area").toString());
                                environmentAttribute.setShapeLeng(object.get("Shape_Leng").toString());
                            } else {
                                return null;
                            }
                        }
                        environmentAttributeList.add(environmentAttribute);
                    } else {
                        errors.add("环境管控编码为空。");
                    }
                }
                if (isExist) {
                    cityCode = HJDYBMTemp1.substring(2, 6);
                } else {
                    cityCode = HJDYBMTemp.substring(2, 8);
                }
            }
        }
        if (errors.size() > 0) {
            resultMap.put("error", errors);
        }
        if (environmentAttributeList.size() > 0) {
            resultMap.put("attribute", environmentAttributeList);
            resultMap.put("cityCode", cityCode);
        }
        return resultMap;
    }
}
